<template>
    <view class="detail-container">
        <!-- 商品图片 -->
        <swiper class="swiper" v-if="swiperHeight" :style="{height: swiperHeight + 'rpx'}" indicator-dots circular>
            <swiper-item v-for="item in detail.proVideoMaps" :key="item.FImgUrl">
                <video :src="item.FVideoUrl" :poster="item.FImgUrl"></video>
            </swiper-item>
            <swiper-item v-for="(item, index) in detail.proImMaps" :key="item.FImgUrl">
                <image :src="item.FImgUrl" mode="aspectFill"></image>
            </swiper-item>
        </swiper>

        <!-- 商品信息 -->
        <view class="introduce-section">
            <view class="product-info">
                <view class="title">{{detail.data.proName}}</view>
                <!-- <view class="price">¥450/月 起</view> -->
            </view>

            <text class="price">
                {{ price || 0 }}元/月
                <text class="del-price" v-if="price!=originPrice && originPrice > 0">
                    {{ originPrice || 0 }}元
                </text>
            </text>
        </view>



        <!-- 芝麻信用免押金提示 -->
        <view class="credit-info" v-if="detail.data.FZmFlag == '01'">
            <div class="zhima">
                <image src="https://jdkj-1306681707.cos.ap-nanjing.myqcloud.com/S0000260/image/proImg_202505231001564120.png" class="zhima-icon"></image>
                <span> 芝麻信用 | 免押金 </span>
            </div>
        </view>

        <!-- 商户地址 -->
        <!-- <view class="merchant-info">
            <view class="section-title">商户地址</view>
            <view class="merchant-name">厦门晟聚新健康管理有限公司</view>
            <view class="merchant-address">福建省厦门市思明区湖滨南路809号2206室</view>
        </view> -->

        <!-- 配置参数 -->
        <view class="specs">
            <view class="section-title">配置参数</view>
            <view class="spec-item">
                <text class="label">规格</text>
                <text class="value">{{selectSkuInfo.propertyName}}</text>
            </view>
            <!-- <view class="spec-item">
                <text class="label">商品品牌</text>
                <text class="value">宿舍</text>
            </view>
            <view class="spec-item">
                <text class="label">商品类型</text>
                <text class="value">房屋</text>
            </view>
            <view class="spec-item">
                <text class="label">商品型号</text>
                <text class="value">骑士之家</text>
            </view> -->
        </view>


        <view class="detail-desc">
            <view class="d-header"><text>图文详情</text></view>
            <view style="padding: 0 20rpx 20rpx">
                <p v-for="(i, idx) in detail.data.proDescriptArr" :key="idx">{{i}}</p>
            </view>
            <template v-if="detail.proContextText">
                <view v-html="detail.proContextText"></view>
            </template>
            <template v-else>
                <view v-for="(item, des_index) in detail.contextimgMaps" :key="des_index" style="height: auto;width: 100%;">
                    <view><image class="des-img" mode="widthFix" style="" :src="item.FImgUrl" @tap="previewImage(detail.contextimgMaps, des_index)"></image></view>
                </view>
            </template>
            <view class="" style="height: 120rpx;">
                <!-- 占位 -->
            </view>
        </view>

        <!-- 底部操作栏 -->
        <view class="bottom-bar">
            <button class="rent-btn" @click="showSpecPopup">极简租赁</button>
            <view class="safe_bar"></view>
        </view>

        <!-- 规格弹窗 -->
        <uni-popup ref="specPopup" type="bottom">
            <view class="spec-popup">
                <view class="popup-header">
                    <image :src="selectSkuInfo.skuImg" mode="aspectFill" class="product-image"></image>
                    <view class="popup-product-info">
                        <view class="title">{{detail.data.proName}}</view>
                        <view class="price">{{selectSkuInfo.spec}}</view>
                        <view class="selected-price">￥{{price}}元/月</view>
                    </view>
                </view>

                <view class="popup-content">
                    <view class="rent-plan">
                        <view class="section-title">规格</view>
                        <view class="plan-type"
                            :class="{active: item.skuId == actSkuId}"
                            @click="handleSkuClick(item)"
                            v-for="item in detail.data.skuList">
                            {{item.propertyName}}
                        </view>

                    </view>

                    <!-- <view class="rent-package">
                        <view class="section-title">套餐</view>
                        <view class="package-option active">宿舍450元/30天（后付）</view>
                    </view> -->
                    <view class="rent-period">
                        <view class="section-title">租期</view>
                        <view class="period-option active">{{selectSkuInfo.FRentCycleCnt}}期，每期{{selectSkuInfo.FRentCycleDay}}天</view>
                        <view class="login_info">{{tempStep}} _ {{$store.state.user.info.info && $store.state.user.info.info.FPhone}}</view>
                    </view>
                </view>

                <view class="popup-footer">
                    <button class="confirm-btn" @click="createOrder">极简租赁</button>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script setup lang="ts">
import { ref, computed } from "vue"
import { onLoad, onShow } from "@dcloudio/uni-app"
import { getSkuInfo } from '@/api/product'
import { createRentOrder } from '@/api/order'
import { throttle2 } from '@/utils/functions'
import { checkRentUserStatus} from '@/api/user'
import { getLoginStatus } from '@/hooks/login';
import interact from "@/utils/interact"
import { useStore } from 'vuex';
import { addFrontErr } from "@/api/base";


const Store = useStore();

const pageData = {
    proId: '',
    storeNo: '',
}

const selectSkuInfo = computed(() => {
    let skuList: any[] = detail.value.data.skuList
    let skuInfo = skuList.find((i: any) => i.skuId == actSkuId.value)
    return skuInfo || {}
})


const price = computed(() => {
    let price = selectSkuInfo.value.userPrice
    if(selectSkuInfo.value.activityPrice && selectSkuInfo.value.isGroupBuy != '01') {
        price = selectSkuInfo.value.activityPrice;
    }
    return +price
})

const originPrice = computed(() => {
    let _originPrice = ''
    if(selectSkuInfo.value.activityPrice && selectSkuInfo.value.isGroupBuy != '01') {
        _originPrice = selectSkuInfo.value.userPrice;
    }
    _originPrice = selectSkuInfo.value.originPrice;
    return +_originPrice
})

onLoad((options: any) => {
    pageData.proId = options.proId
    pageData.storeNo = options.storeNo
    actSkuId.value = options.skuId
    getProDetail()
})

const detail = ref<any>({
    data: {
        skuList: []
    },
})
const swiperHeight = ref(750)
const actSkuId = ref('')
const getProDetail = () => {
    getSkuInfo({
        proId: pageData.proId,
        reatelSale: '1',
        storeNo: pageData.storeNo,
        proStoreNo: pageData.storeNo
    }).then((res) => {
        let allBanners = res.data.proImMaps
        let bannerImgs: any = allBanners.filter((i: any) => !i.FVideoUrl)
        let bannerVideos: any = allBanners.filter((i: any) => i.FVideoUrl)
        res.data.proImMaps = bannerImgs
        res.data.proVideoMaps = bannerVideos || []

        // 设置swiper的高度
        let bannserImgUrl;
        if(res.data.proImMaps.length) {
            bannserImgUrl = res.data.proImMaps[0] && res.data.proImMaps[0].FImgUrl
        } else if(res.data.proVideoMaps.length) {
            let firstVideo = res.data.proVideoMaps[0]
            if(firstVideo.FImgUrl) {
                bannserImgUrl = firstVideo.FImgUrl
            }
        }

        if(bannserImgUrl) {
            getImgTemp(bannserImgUrl).then(info => {
                swiperHeight.value = ( info.height / info.width) * 750
            })
        } else {
            swiperHeight.value = 750
        }
        if( res.data.data.proDescript ) {
            res.data.data.proDescriptArr = res.data.data.proDescript.split('\n') // ↵
        }
        if(!actSkuId.value || res.data.data.skuList.findIndex((i: any) => i.skuId == actSkuId.value) == -1) {
            actSkuId.value = res.data.data.skuList[0].skuId;
        }

        let goodsDetail = res.data
        // goodsDetail.proServerTemplates = res.data.data.proServerTemplates
        // if(goodsDetail.proServerTemplates && goodsDetail.proServerTemplates.length) {
        //     let str = ''
        //     goodsDetail.proServerTemplates.forEach((item: any) => {
        //         str += item.title + ' · '
        //     })
        //     goodsDetail.proServerTemp = str.slice(0, str.length - 2)
        // }
        // goodsDetail.data.skuList.forEach((item: any, index: number) => {
        //     if(item.skuId == actSkuId.value) {
        //         if(item.skuPhase) {
        //             let rangPrice = []
        //             try{
        //                 rangPrice = JSON.parse(item.skuPhase) || []
        //             } catch(err) { }
        //             rangPrice.forEach((item: any) => {
        //                 item.minNum = +item.minNum
        //                 item.maxNum = +item.maxNum
        //                 item.price = +item.price
        //             })
        //             if(rangPrice.length) {
        //                 item.rangPrice = rangPrice
        //             }
        //         }
        //     }
        // })

        if(goodsDetail.proContextText) {
            let fArtContext = goodsDetail.proContextText
            fArtContext = replaceSpecialChar(fArtContext)
            fArtContext = fArtContext.replace(/\<img/gi, '<img style="max-width: 100%; height: auto"')
            fArtContext = fArtContext.replace(/(<p)/ig, '|$1')
            let contentArr = fArtContext.split('|')
            contentArr.forEach((item: string, index: number) => {
                if(/<img.*?src=/ig.test(item) && item.indexOf('indent') > -1) {
                    contentArr[index] = item.replace(/(<p .*?)text-indent.*?;(.*?<img)/,'$1$2' )
                }
            })
            fArtContext = contentArr.join('')
            goodsDetail.proContextText = fArtContext
        }

        detail.value = goodsDetail
        console.log(detail.value);


    })
}




function replaceSpecialChar(detail: string) {
    var content = detail.replace(/<img[^>]*>/gi, function(match, capture) {
        var match = match.replace(/(style="(.*?)")|(width="(.*?)")|(height="(.*?)")/ig,'style="max-width: 100%; height: auto"');
        return match;
    });
    return content;
}

function getImgTemp(src: string) {
    return new Promise<UniApp.GetImageInfoSuccessData>((resolve, reject) => {
        uni.getImageInfo({
            src,
            success(res) {
                resolve(res)
            },
            fail(err) {
                uni.hideLoading()
                reject(err)
            },
        })
    })
}

const previewImage = (imgs: any[], index: number) => {
    let urls = imgs.map(v => v.FImgUrl);
    uni.previewImage({
        urls: urls,
        current: urls[index]
    });
}


const handleSkuClick = (skuItem: any) => {
    actSkuId.value = skuItem.skuId
}

const checkAuth = () => {
    return new Promise(async (resolve, reject) => {
        tempStep.value = '0'
        // 前端需要先判断一下实名认证
        uni.showLoading({ mask: true })

        tempStep.value = '1'
        let loginStatus = await getLoginStatus(true)
        tempStep.value = '2'
        if(!loginStatus) return uni.hideLoading();
        tempStep.value = '3'
        try {
            tempStep.value = '4'
            let checkRes = await checkRentUserStatus({ storeNo: pageData.storeNo || '' })
            tempStep.value = '5'
            let authData = checkRes.data
            tempStep.value = '6'
            if(authData?.realNameInfo?.realStatus != '01') {
                tempStep.value = '7'
                try {
                    let action = await interact.modal({
                        title: '温馨提示',
                        message: '请先进行实名认证',
                        showCancel: true,
                        confirmText: '去认证',
                    })
                    Store.commit('control/SET_CREATE_ORDER_PROMISE_RESOLVE', resolve)
                    tempStep.value = '8'
                    if(action.confirm) {
                        tempStep.value = '9'
                        uni.navigateTo({
                            url: '/pages/user/realAuth?from=order'
                        })
                    }
                } catch(err) {
                    tempStep.value = '8.1'
                    Store.commit('control/SET_CREATE_ORDER_PROMISE_RESOLVE', resolve)
                    uni.navigateTo({
                        url: '/pages/user/realAuth?from=order'
                    })
                }
                return uni.hideLoading()
            }

            if(!authData?.relationCnt || authData?.relationCnt < 2) {
                tempStep.value = '10'
                let action = await interact.modal({
                    title: '温馨提示',
                    message: '请完善至少2条紧急联系人',
                    showCancel: true,
                    confirmText: '去完善',
                })
                Store.commit('control/SET_CREATE_ORDER_PROMISE_RESOLVE', resolve)
                tempStep.value = '11'
                if(action.confirm) {
                    tempStep.value = '12'
                    uni.navigateTo({
                        url: '/pages/user/relationList?from=order'
                    })
                }
                tempStep.value = '13'
                return uni.hideLoading()
            }
            resolve(true)
        } catch(err: any) {
            uni.hideLoading()
            interact.toast((err && (err.msg || err.message || err)) || '')
            addFrontErr({
                errMsg: JSON.stringify({
                    msg: '创建订单界面报错',
                    UUID: uni.getStorageSync('__DC_STAT_UUID'),
                    message: err?.message || err || '',
                    stack: err.stack || '',
                    api: err.api || '',
                    SDKVersion: uni.SDKVersion,
                }),
                platform: "zulin_ali_err",
                remark: '创建订单界面报错',
            });
        }
    })
}







const tempStep = ref('0')
const createOrder = throttle2(async function(){
    let authRes = await checkAuth()
    tempStep.value = '14'
    let reqData = {
        orderSource: '00',
        storeNo: pageData.storeNo || Store.state.shop.storeNo,
        proStoreNo: pageData.storeNo || Store.state.shop.storeNo,
        recType: '01',
        serviceFlag: '6',
        linkSysUserId: Store.state.shop.tempLinkSysUserId,
        skuData: JSON.stringify([{
            skuId: actSkuId.value,
            num: 1
        }])
    }
    tempStep.value = '15'
    console.log(reqData);
    let createRes = await createRentOrder(reqData)
    let orderData = createRes.data
    tempStep.value = '16'
    if(authRes == 'relactionship') {
        uni.redirectTo({
            url: `/pages/order/pay?orderNo=${orderData.orderNo}`
        })
    } else {
        uni.navigateTo({
            url: `/pages/order/pay?orderNo=${orderData.orderNo}`
        })
    }

    // getPayType({
    //     payType: 'ALIMINI',
    //     storeNo: pageData.storeNo || Store.state.shop.storeNo,
    // })

    // collect({
    //     collectMoney: selectSkuInfo.value.FFixedPrice,
    //     orderNo: orderData.orderNo,
    //     payTypeId: await this.getPayType()
    // })
    // console.log(orderData);
}, 1000)


const specPopup = ref()
const showSpecPopup = () => {
    console.log(specPopup.value);

    specPopup.value.open()
}


</script>

<style lang="scss" scoped>
.detail-container {
    padding-bottom: 120rpx;
}

.swiper {
    width: 100%;
    height: 750rpx;

    image, video {
        width: 100%;
        height: 100%;
    }
}

.product-info {
    margin-bottom: 20rpx;
    .title {
        font-size: 32rpx;
        font-weight: bold;
    }

    .price {
        color: #ff4d4f;
        font-size: 36rpx;
        margin-top: 10rpx;
    }
}

.credit-info {
    display: flex;
    align-items: center;
    padding: 20rpx;
    .zhima {
        display: flex;
        align-items: center;
        font-size: 30rpx;
        border: 1px solid #1890ff;
        border-radius: 10rpx;
        line-height: 36rpx;
        color: #1890ff;
        padding: 0 15rpx;
        .zhima-icon {
            width: 30rpx;
            height: 36rpx;
            flex-shrink: 0;
            margin-right: 8rpx;
        }
    }
}

.merchant-info, .specs {
    padding: 20rpx;
    margin-top: 20rpx;
    background: #fff;

    .section-title {
        font-size: 28rpx;
        font-weight: bold;
        margin-bottom: 20rpx;
    }
}

.spec-item {
    display: flex;
    justify-content: space-between;
    padding: 10rpx 0;

    .label {
        color: #666;
    }
}
.login_info{
    font-size: 20rpx;
    color: #eee;
}
.bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx 20rpx 0 20rpx;
    background: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);

    .rent-btn {
        width: 100%;
        background: #1890ff;
        color: #fff;
    }
    .safe_bar{
        width: 100%;
        height: env(safe-area-inset-bottom);
        padding-bottom: 20rpx;
        box-sizing: border-box;
    }
}

.spec-popup {
    background: #fff;
    border-radius: 20rpx 20rpx 0 0;

    .popup-header {
        padding: 20rpx;
        display: flex;

        .product-image {
            width: 200rpx;
            height: 200rpx;
            border-radius: 10rpx;
        }

        .popup-product-info {
            flex: 1;
            padding-left: 20rpx;

            .title {
                font-size: 28rpx;
            }

            .price, .selected-price {
                color: #ff4d4f;
                margin-top: 10rpx;
            }
        }
    }

    .popup-content {
        padding: 20rpx;

        .section-title {
            font-size: 28rpx;
            margin: 20rpx 0;
        }

        .plan-type, .package-option, .period-option {
            display: inline-block;
            padding: 10rpx 20rpx;
            border: 1rpx solid #ddd;
            border-radius: 10rpx;
            margin-right: 20rpx;
            margin-bottom: 20rpx;

            &.active {
                border-color: #1890ff;
                color: #1890ff;
                background: #f0f9ff;
            }
        }
    }

    .popup-footer {
        padding: 20rpx;

        .confirm-btn {
            width: 100%;
            background: #1890ff;
            color: #fff;
        }
    }
}






.introduce-section {
    position: sticky;
    top: 0px;
    z-index: 2;
	background: #fff;
	padding: 20rpx 32rpx;
	font-weight: bold;
	display: flex;
	flex-direction: column;
	justify-content: flex-start;
    .activity_price_box{
        width: 100%;
        border-radius: 10rpx;
        @include gradient(#dc3b40, #ff6b70);
        display: flex;
        padding: 10rpx;
        margin-bottom: 20rpx;
        >div{
            color: #fff;
            @include align(h-center, column);
            p{
                font-weight: bold;
                line-height: 40rpx;
                margin-bottom: 6rpx;
            }
            span{
                font-size: 24rpx;
            }
            &.activity_price{
                flex: 1;
                p{
                    font-size: 40rpx;
                }
                span{
                    text-decoration: line-through;
                }
            }
            &.activity_timer{
                text-align: right;
                p{
                    font-size: 32rpx;
                }
                span{
                    font-size: 26rpx;
                }
            }

        }
    }
	.proDesc-box {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 20rpx;
	}
	.proDesc {
		font-size: 24rpx;
		color: #909399;
	}
	.proDesc-all {
		font-size: 24rpx;
		display: inline-block;
		color: #909399;
	}
	.specTxt{
        display: flex;
        align-items: center;
        justify-content: space-between;
		color: #666;
		font-size: 30rpx;
        margin-top: 10rpx;
	}
    .specTxt-btn {
        border-radius: 40rpx;
        font-size: 28rpx;
        padding: 8rpx 16rpx;
        color: #fff;
    }

	.title {
		display: flex;
		font-size: 36rpx;
		color: #000000;
	}

	.price-box {
		display: flex;
		align-items: baseline;
		height: 64rpx;
		padding: 10rpx 0;
		font-size: 26rpx;
		color: #ff3333;
	}

	.price {
        font-size: 34rpx;
        color: #ff3333;
	}
    .del-price {
        font-size: 28rpx;
        color: #666;
    }
    .group-price {
        margin-left: 30rpx;
        font-size: 24rpx;
        color: #ee7c33;
    }

	.m-price {
		margin: 0 12rpx;
		color: #909399;
		text-decoration: line-through;
	}

	.coupon-tip {
		align-items: center;
		padding: 4rpx 10rpx;
		background: #ff3333;
		font-size: 24rpx;
		color: #fff;
		border-radius: 6rpx;
		line-height: 1;
		transform: translateY(-4rpx);
	}

	.bot-row {
		display: flex;
		align-items: center;
		height: 50rpx;
		font-size: 24rpx;
		color: #909399;

		text {
			flex: 1;
		}
	}
}


/*  详情 */
.detail-desc {
	background: #fff;
	// margin-top: 16rpx;
	.d-header {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 80rpx;
		font-size: 28rpx;
		color: #999999;
		position: relative;
		text {
			padding: 0 20rpx;
			background: #fff;
			position: relative;
			// z-index: 1;
		}
		&:after {
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translateX(-50%);
			width: 300rpx;
			height: 0;
			content: '';
			border-bottom: 1px solid #ccc;
		}
	}

	.des-img {
		width: 100%;
		display: block;
	}
}

</style>
